package org.adorsys.aderp.cash.init;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.adorsys.aderp.cash.service.CashRegisterDataService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ServletContextAware;

public class DataLoaderService implements ServletContextAware {
	@Resource
	private CashRegisterDataService cashRegisterDataService;
	@Resource
	private CashInitFiles cashInitFiles;
		
	private ServletContext servletContext;
	
	@Transactional
	public void initApplication() {
		
		List<String> orgaFiles = cashInitFiles.getInitFiles();
		for (String dataXLS : orgaFiles) {
			InputStream inputStream = servletContext.getResourceAsStream(dataXLS);
	        InputStream inputXLS = new BufferedInputStream(inputStream);
	        cashRegisterDataService.importDataXLS(inputXLS);

	        try {
				inputXLS.close();
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
